import { connect, type ChannelModel, type Channel, ConsumeMessage } from 'amqplib'
import logger from './logger'

let connection: ChannelModel
let channel: Channel

// 连接到rabbitmq
const connectToRabbitMQ = async (queueName: string = 'dami_stu') => {
  if (connection && channel) return
  try {
    connection = await connect(process.env.RABBITMQ_URL as string)
    channel = await connection.createChannel()
    await channel.assertQueue(queueName, { durable: true })
    console.log('rabbitmq 连接成功')
  } catch (error) {
    logger.error(`[${queueName}]RabbitMQ连接失败：`, error)
  }
}

/** 队列生产者(发送消息) */
export const queueProducer = async (msg: any, queueName: string = 'dami_stu') => {
  try {
    await connectToRabbitMQ(queueName)
    channel.sendToQueue(queueName, Buffer.from(JSON.stringify(msg)), { persistent: true })
  } catch (error) {
    logger.error(`[${queueName}]mq队列生产者错误：`, error)
  }
}

/** 队列消费者（接收消息） */
export const queueConsumer = async (
  callback: (msg: ConsumeMessage) => Promise<void>,
  queueName: string = 'dami_stu',
) => {
  try {
    await connectToRabbitMQ(queueName)
    channel.consume(
      queueName,
      async (msg) => {
        if (msg && callback) {
          await callback(msg)
        }
      },
      {
        noAck: true,
      },
    )
  } catch (error) {
    logger.error(`[${queueName}]mq队列消费者错误：`, error)
  }
}
